package com.cloudlead.utils.messages.push;

import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.exception.ChannelClientException;
import com.baidu.yun.channel.exception.ChannelServerException;
import com.baidu.yun.channel.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * Created by Dean on 2015/4/24.
 */
public class PushMessageClient implements PushMessageApi {
    final Logger logger = LoggerFactory.getLogger(this.getClass());

    private BaiduChannelClient channelClient;

    public PushMessageClient(String apiKey, String secretKey) {
        ChannelKeyPair pair = new ChannelKeyPair(apiKey, secretKey);

        //  创建BaiduChannelClient对象实例
        channelClient = new BaiduChannelClient(pair);

        //  若要了解交互细节，请注册YunLogHandler类
        channelClient.setChannelLogHandler(event -> logger.debug(event.getMessage()));
    }

    @Override
    public int pushMessage(String message, String userId, Long channelId, int deviceType, String sound) {
        Assert.hasText(message, "message is required.");
        Assert.hasText(userId, "userId is required.");
        Assert.isTrue(deviceType > 0 && deviceType < 6, "deviceType is invalid.");
        try {
            //  创建请求类对象
            PushUnicastMessageRequest request = new PushUnicastMessageRequest();
            request.setDeviceType(deviceType); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setChannelId(channelId);
            request.setUserId(userId);

            if (4 == deviceType) {
                request.setMessageType(1);
                request.setDeployStatus(2);
                String soundMsg = "";
                if (StringUtils.hasText(sound)) {
                    soundMsg = ", \"sound\" : \"" + sound + "\"";
                }
                request.setMessage("{ \"aps\" : {\"alert\" : \"" + message + " \", \"badge\" : 1 " + soundMsg + " } }");
            } else {
                request.setMessageType(0);
                request.setMessage(message);
            }

            //  调用pushMessage接口
            PushUnicastMessageResponse response = channelClient
                    .pushUnicastMessage(request);

            return response.getSuccessAmount();

        } catch (ChannelClientException e) {
            e.printStackTrace();
            throw new MessagePushClientException(e);
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
            logger.error(String.format(
                    "request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            throw new MessagePushServerException(e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }
    }

    @Override
    public int pushBroadcastMessage(String title, String message, boolean hasNotify, String tag, int deviceType) {
        Assert.hasText(message, "message is required.");
        Assert.isTrue(deviceType > 0 && deviceType < 6, "deviceType is invalid.");
        try {
            if (StringUtils.hasText(tag)) {
                //  创建请求类对象
                PushTagMessageRequest request = new PushTagMessageRequest();
                request.setDeviceType(deviceType); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
                request.setTagName(tag);

                if (hasNotify) {
                    request.setMessageType(1);
                    request.setMessage("{\"title\":\"" + title + "\",\"description\":\"" + message + "\"}");
                } else {
                    request.setMessageType(0);
                    request.setMessage(message);
                }

                // 5. 调用pushMessage接口
                PushTagMessageResponse response = channelClient
                        .pushTagMessage(request);
                return response.getSuccessAmount();
            } else {
                //  创建请求类对象
                PushBroadcastMessageRequest request = new PushBroadcastMessageRequest();
                request.setDeviceType(deviceType); // device_type => 1: web 2: pc 3:android 4:ios 5:wp


                if (hasNotify) {
                    request.setMessageType(1);
                    request.setMessage("{\"title\":\"" + title + "\",\"description\":\"" + message + "\"}");
                } else {
                    request.setMessageType(0);
                    request.setMessage(message);
                }

                //  调用pushMessage接口
                PushBroadcastMessageResponse response = channelClient
                        .pushBroadcastMessage(request);

                return response.getSuccessAmount();
            }


        } catch (ChannelClientException e) {
            e.printStackTrace();
            throw new MessagePushClientException(e);
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
            logger.error(String.format(
                    "request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            throw new MessagePushServerException(e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }
    }

    @Override
    public void bindTag(String tag, String userId) {
        Assert.hasText(tag, "tag is required.");
        Assert.hasText(userId, "userId is required.");
        try {
            SetTagRequest request = new SetTagRequest();
            request.setTag(tag);
            request.setUserId(userId);

            channelClient.setTag(request);
        } catch (ChannelClientException e) {
            e.printStackTrace();
            throw new MessagePushClientException(e);
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
            logger.error(String.format(
                    "request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            throw new MessagePushServerException(e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }

    }

    @Override
    public void unbindTag(String tag, String userId) {
        try {
            DeleteTagRequest request = new DeleteTagRequest();
            request.setTag(tag);
            request.setUserId(userId);

            channelClient.deleteTag(request);
        } catch (ChannelClientException e) {
            e.printStackTrace();
            throw new MessagePushClientException(e);
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
            logger.error(String.format(
                    "request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            throw new MessagePushServerException(e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }
    }
}
